import 'dart:math';

import 'package:flutter/material.dart';
import 'package:klfz_flutter/book/book_read/logic.dart';
import 'package:klfz_flutter/book/widgets/reader_page_agent.dart';
import 'package:klfz_flutter/config/ReaderConfig.dart';
import 'package:klfz_flutter/http/http_utils.dart';
import 'package:klfz_flutter/model/chapter_result.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
//当前页 第一页 最后一页
enum PageJumpType { stay, firstPage, lastPage}

class ContentLayer extends StatefulWidget {
  final Chapter? chapter;
  ContentLayer({Key? key, this.chapter}) : super(key: key);
  @override
  _ContentLayerState createState() => _ContentLayerState();
}

class _ContentLayerState extends State<ContentLayer> {

  final BookReadLogic logic = Get.put(BookReadLogic());

  //当前页
  int pageIndex = 1;
  //总章节数
  int totalPage = 0;
  //显示menu工具栏
  bool isMenuVisiable = false;
  List chapterDetail = [];
  //当前章节
  late Chapter currentChapter;
  //上一章节
  Chapter? preChapter;
  //下一章节
  Chapter? nextChapter;
  //前往下一章节
  late bool gotoNext = true;
  PageController _pageController = new PageController();
  PageJumpType _pageJumpType = PageJumpType.firstPage;
  @override
  void initState() {
    currentChapter = this.widget.chapter!;
    totalPage = currentChapter.totalPage;
    loadData(currentChapter);
    _pageController.addListener(onScroll);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    final size =MediaQuery.of(context).size;
    return SafeArea(
      child: GestureDetector(
        onTapUp: (TapUpDetails details) {
          onTap(details.globalPosition, size);
        },
        child: Container(
          color: Colors.transparent,
          margin: EdgeInsets.only(left: 15, right: 15, top: 30, bottom: 30),
          child: currentChapter != null ? PageView.builder(
              controller: _pageController,
              physics: const BouncingScrollPhysics(),
              scrollDirection: Axis.horizontal,
              itemCount: currentChapter.pageCount,
              itemBuilder: (ctx, index) {
                return Container(
                  child: Text.rich(
                      TextSpan(children: [
                        TextSpan(text: currentChapter.stringAtPageIndex(index), style: TextStyle(fontSize: 14))
                      ])
                  ),
                );
              }
          ) : Container()
        ),
      ),
    );
  }

  onTap(Offset position, Size size) async {
    double xRate = position.dx / size.width;
    if (xRate > 0.33 && xRate < 0.66) {
      // SystemChrome.setEnabledSystemUIOverlays([SystemUiOverlay.top, SystemUiOverlay.bottom]);
      // setState(() {
      //   isMenuVisiable = true;
      // });
    } else if (xRate >= 0.66) {
      nextPage();
    } else {
      previousPage();
    }
  }

  nextPage() {
    pageIndex += pageIndex;
    logic.updateCurrentPage(pageIndex + 1, currentChapter.id!);
    _pageController.nextPage(duration: Duration(milliseconds: 250), curve: Curves.easeOut);

  }

  previousPage() {
    pageIndex -= pageIndex;
    // print("previousPage");
    // logic.updateCurrentPage(pageIndex + 1, currentChapter.id!);
    _pageController.previousPage(duration: Duration(milliseconds: 250), curve: Curves.easeOut);
  }

  onScroll() {
    // print("当前章节id：" + currentChapter.id.toString());
    // print("总章节：" + totalPage.toString());
    //页数
    double page = _pageController.offset / (ScreenUtil().screenWidth - 30);
    // print("当前页：" + page.toString());
    // print("总页数：" + currentChapter.pageCount.toString());
    //如果是最后一页 并且不是最后一章
    if (page == currentChapter.pageCount && currentChapter.id != totalPage) {
      print('到达下个章节了');
      logic.updateCurrentPage(1, currentChapter.id! + 1);
      preChapter = currentChapter;
      ReaderConfig.getChapterbyId(currentChapter.id! + 1).then((value) {
        _pageController.jumpToPage(0);
        currentChapter = logic.getPages(value, 14);
        pageIndex = 1;
        setState(() {});
      });
      ReaderConfig.getChapterbyId(currentChapter.id! + 2).then((value) {
        nextChapter = logic.getPages(value, 14);
      });
    }
    //最后一页也是最后一章
    if (page == currentChapter.pageCount && currentChapter.id == totalPage) {
      print("此小说已阅读完毕");
    }
    //第一页也是第一章
    if (page == 0 && currentChapter.id == 1) {
      print("到头了");
    }

    if (nextChapter != null && page == 0 && currentChapter.id != 1) {
      print('到达上个章节了 前往最后一页');
      currentChapter = preChapter!;
      _pageController.jumpToPage(preChapter!.pageCount - 1);
      pageIndex = preChapter!.pageCount - 1;
      setState(() {
      });
      // nextArticle = currentArticle;
      // currentArticle = preArticle;
      // preArticle = null;
      // pageIndex = currentArticle.pageCount - 1;
      // pageController.jumpToPage(currentArticle.pageCount - 1);
      // fetchPreviousArticle(currentArticle.preArticleId);
      // setState(() {});
    }
  }

  loadData(Chapter currentChapter) {
    //如果非第一章，则请求上一章数据
    if (currentChapter.id! > 1) {
      ReaderConfig.getChapterbyId(currentChapter.id! - 1).then((value) {
        preChapter =  logic.getPages(value, 14);
      });
    } else {
      preChapter = null;
    }
    //如果当前章有下一章（totalpage判断）
    if (currentChapter.id! < totalPage) {
      print(currentChapter.id! + 1);
      ReaderConfig.getChapterbyId(currentChapter.id! + 1).then((value) {
        nextChapter = logic.getPages(value, 14);
      });
    } else {
      nextChapter = null;
    }
  }



}
